import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
import jwt_sign from 'jsonwebtoken'

const prisma = new PrismaClient()

export class UserService {
    static async register(email: string, password: string, name?: string) {
        const existingUser = await prisma.user.findUnique({
            where: { email }
        })

        if (existingUser) {
            throw new Error('邮箱已被注册')
        }

        const hashedPassword = await bcrypt.hash(password, 10)

        const user = await prisma.user.create({
            data: {
                email,
                password: hashedPassword,
                name
            }
        })

        const token = jwt_sign.sign({ userId: user.id }, process.env.JWT_SECRET!)
        return { token }
    }

    static async login(email: string, password: string) {
        const user = await prisma.user.findUnique({
            where: { email }
        })

        if (!user) {
            throw new Error('用户不存在')
        }

        const validPassword = await bcrypt.compare(password, user.password)
        if (!validPassword) {
            throw new Error('密码错误')
        }

        const token = jwt_sign.sign({ userId: user.id }, process.env.JWT_SECRET!)
        return { token }
    }

    static async getProfile(userId: string) {
        return prisma.user.findUnique({
            where: { id: userId },
            select: { id: true, email: true, name: true }
        })
    }
} 